/*
 * Copyright 2006-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.graphnav.aggregator.storage.impl.jenastorage;

import org.graphnav.aggregator.storage.StorageFactory;
import org.graphnav.aggregator.storage.Storage;
import org.graphnav.aggregator.storage.StorageFactoryException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Model;

/**
 * The Jena Storage factory.
 */
public class JenaStorageFactory implements StorageFactory {

    static final String MODEL_BASE = "jenamodel:";

    private static JenaStorageFactory instance  = null;

    private JenaStorageFactory() {}

    public static JenaStorageFactory getInstance() {
        if(instance == null) {
            instance = new JenaStorageFactory();
        }
        return instance;
    }
    
    public JenaStorage openStorage(File file) throws StorageFactoryException {
        Model model = ModelFactory.createDefaultModel();
        if( file.exists() ) {
            try {
                model.read( new FileInputStream(file), MODEL_BASE + file.getAbsoluteFile() );
            } catch (FileNotFoundException e) {
                throw new StorageFactoryException(e);
            }
        }
        JenaStorage js = new JenaStorage(model, file);
        return js;
    }

    public void saveStorage(Storage storage) throws StorageFactoryException {
        JenaStorage js = (JenaStorage) storage;
        Model model = js.getModel();
        try {
            model.write( new FileOutputStream( js.getFile() ) );
        } catch (FileNotFoundException e) {
            throw new StorageFactoryException(e);
        }
    }

    public void disposeStorage(Storage storage) {
        JenaStorage js = (JenaStorage) storage;
        js.getModel().close();
    }
}
